package com.qf.service.impl;

import com.qf.config.IdWorker;
import com.qf.constant.CacheConstants;
import com.qf.constant.RabbitMQConstants;
import com.qf.constant.ReportStateConstants;
import com.qf.constant.SourceType;
import com.qf.enums.InterfaceExceptionEnums;
import com.qf.feign.CacheFeign;
import com.qf.form.SmsInterfaceForm;
import com.qf.model.StandardSubmit;
import com.qf.service.SmsService;
import com.qf.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author YDW
 * projectName:project2202_4
 * time:2022/6/19 23:23
 * description:
 */
@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    CacheFeign cacheFeign;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    IdWorker idWorker;



    //发送短信消息到消息队列
    @Override
    public Result sendSMS(SmsInterfaceForm interfaceForm) {
        Result result=this.checkInterfaceForm(interfaceForm);

        if (result != null) {
            return result;
        }
        //客户端id
        String clientID = interfaceForm.getClientID();

        //根据客户端id客户端信息
        String key= CacheConstants.CACHE_PREFIX_CLIENT +clientID;

        Map<String,String> map = cacheFeign.hMGet(key);


        String srcID = interfaceForm.getSrcID();
        Long srcid=null;
        if (!StringUtils.isEmpty(srcID)) {
            try {
                srcid = Long.parseLong(srcID);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                log.info("[接口模块--数据校验]"+InterfaceExceptionEnums.INTERFACE_SRC_ID_ERROR.getMessage());
                return Result.error(InterfaceExceptionEnums.INTERFACE_SRC_ID_ERROR);
            }
        }
        //校验通过后，把发送短信的请求转发到mq

        String mobiles = interfaceForm.getMobile();
        String[] arr = mobiles.split(",");

        //每个手机号都需要发送一条端（一个mq消息）
        for (String mobile : arr) {
            StandardSubmit submit=new StandardSubmit();
            //设置唯一的id
            submit.setSequenceId(String.valueOf(idWorker.nextId()));
            //设置SrcId
            submit.setSrcSequenceId(srcid);
            //发送时间
            submit.setSendTime(new Date());
            //设置客户端id
            submit.setClientID(Integer.parseInt(interfaceForm.getClientID()));
            //设置短信内容
            submit.setMessageContent(interfaceForm.getContent());
            //设置短信的优先级
            String priority = map.get("priority");
            submit.setMessagePriority(Short.parseShort(priority));
            //设置目标手机号
            submit.setDestMobile(mobile);
            //短信的来源
            submit.setSource(SourceType.HTTP);
            //设置短信状态
            submit.setReportState(ReportStateConstants.WAIT);


            rabbitTemplate.convertAndSend(RabbitMQConstants.TOPIC_PRE_SEND + "_exchange","routingKey",submit);
        }




        return Result.ok("操作成功");
    }

    private Result checkInterfaceForm(SmsInterfaceForm interfaceForm) {

        //客户端id
        String clientID = interfaceForm.getClientID();

        //根据客户端id客户端信息
        String key= CacheConstants.CACHE_PREFIX_CLIENT +clientID;

        Map<String,String> map = cacheFeign.hMGet(key);
        //判断是否有此客户端
        if(map==null||map.size()==0){
            log.info("[接口模块--数据校验]"+InterfaceExceptionEnums.INTERFACE_CLIENT_ID_ERROR.getMessage());
            return Result.error(InterfaceExceptionEnums.INTERFACE_CLIENT_ID_ERROR);
        }

        //判断密码是否正确
        String pwd = interfaceForm.getPwd();
        String pwd1 = map.get("pwd");
        if(StringUtils.isEmpty(pwd) || !pwd.equals(pwd1)){

            log.info("[接口模块--数据校验]"+InterfaceExceptionEnums.INTERFACE_PWD_ERROR.getMessage());
            return Result.error(InterfaceExceptionEnums.INTERFACE_PWD_ERROR);
        }

        //发起请求的ip
        String ip = interfaceForm.getIp();
        boolean flag=false;
        //校验ip是否在白名单内
        String ipaddress = map.get("ipaddress");
        if(!StringUtils.isEmpty(ipaddress)){
            String[] ipArr = ipaddress.split(",");
            for (String s : ipArr) {
                if (ip.equalsIgnoreCase(s)){
                    flag=true;
                }
            }
        }
        //如果flag为false， 说明不再白名单范围内
        if(!flag){
            log.info("[接口模块--数据校验]"+InterfaceExceptionEnums.INTERFACE_IP_ERROR.getMessage());
            return Result.error(InterfaceExceptionEnums.INTERFACE_IP_ERROR);
        }


        //判断内容是否超过500字
        String content = interfaceForm.getContent();
        if(StringUtils.isEmpty(content)||content.length()>500){
            log.info("[接口模块--数据校验]"+InterfaceExceptionEnums.INTERFACE_CONTENT_ERROR.getMessage());
            return Result.error(InterfaceExceptionEnums.INTERFACE_CONTENT_ERROR);
        }



        //校验手机号
        String mobiles = interfaceForm.getMobile();
        if(StringUtils.isEmpty(mobiles)){
            log.info("[接口模块--数据校验]"+InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR.getMessage());
            return Result.error(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR);
        }
        //如果不为空，以逗号分隔
        String[] mobileArr = mobiles.split(",");
        if(mobileArr.length==0||mobileArr.length>100){
            log.info("[接口模块--数据校验]"+InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR.getMessage());
            return Result.error(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR);
        }
        List<String> errorMobiles=new ArrayList<>();
        //校验手机号的正则表达式
        String regex = "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
        for (String mobile : mobileArr) {
            //如果不匹配手机号格式
            if (!mobile.matches(regex)){
                //添加错误手机号到list集合中
                errorMobiles.add(mobile);
            }
        }
        //如果手机号码不符合要求， 返回手机号码错误，同时包含错误手机号
        if(errorMobiles.size()>0){
            log.info("[接口模块--数据校验]"+InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR.getMessage()+",错误手机号码为:{}",errorMobiles);
            return Result.error(InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR.getCode(),InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR.getMessage()+",错误手机号码为:"+errorMobiles);
        }

        return null;
    }
}
